package com.meiyuetao.myt.core.web;

import java.io.Serializable;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lab.s2jh.auth.entity.Department;
import lab.s2jh.auth.entity.User;
import lab.s2jh.auth.security.AuthUserHolder;
import lab.s2jh.auth.service.DepartmentService;
import lab.s2jh.auth.service.UserService;
import lab.s2jh.core.context.SpringContextHolder;
import lab.s2jh.core.entity.BaseEntity;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AuthContextHolder;
import lab.s2jh.core.security.AuthUserDetails;
import lab.s2jh.sys.service.DataDictService;
import lab.s2jh.web.action.BaseController;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.meiyuetao.myt.md.entity.Brand;
import com.meiyuetao.myt.md.entity.Category;
import com.meiyuetao.myt.md.entity.Floor;
import com.meiyuetao.myt.md.entity.Region;
import com.meiyuetao.myt.md.service.BrandService;
import com.meiyuetao.myt.md.service.CategoryService;
import com.meiyuetao.myt.md.service.FloorService;
import com.meiyuetao.myt.md.service.RegionService;
import com.meiyuetao.myt.partner.dao.PartnerDao;
import com.meiyuetao.myt.partner.entity.Partner;
import com.meiyuetao.myt.partner.entity.Partner.PartnerTypeEnum;
import com.meiyuetao.myt.partner.service.PartnerService;
import com.meiyuetao.myt.purchase.entity.Supplier;
import com.meiyuetao.myt.purchase.entity.Supplier.SupplierTypeEnum;
import com.meiyuetao.myt.purchase.service.SupplierService;
import com.meiyuetao.myt.stock.entity.StorageLocation;
import com.meiyuetao.myt.stock.service.StorageLocationService;
import com.meiyuetao.myt.vip.entity.VipLevel;
import com.meiyuetao.myt.vip.service.VipLevelService;

public abstract class MytBaseController<T extends BaseEntity<ID>, ID extends Serializable> extends BaseController<T, ID> {

    @Autowired
    private CategoryService categoryService;
    @Autowired
    private RegionService regionService;
    @Autowired
    private DataDictService dataDictService;
    @Autowired
    private FloorService floorService;
    @Autowired
    private StorageLocationService storageLocationService;
    @Autowired
    private SupplierService supplierService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private UserService userService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private PartnerService partnerService;
    @Autowired
    private VipLevelService vipLevelService;

    public Partner getLogonPartner() {
        PartnerDao partnerDao = SpringContextHolder.getBean(PartnerDao.class);
        AuthUserDetails authUserDetails = AuthContextHolder.getAuthUserDetails();
        Assert.notNull(authUserDetails);
        String aclCode = authUserDetails.getAclCode();
        if (StringUtils.isBlank(aclCode)) {
            return null;
        }
        return partnerDao.findByCode(aclCode);
    }

    public String getImgUrlPrefix() {
        return "http://img.iyoubox.com/GetFileByCode.aspx?code=";
    }

    public String getKindEditorImageUploadUrl() {
        HttpServletRequest request = ServletActionContext.getRequest();
        return request.getContextPath() + "/pub/image-upload!execute;JSESSIONID=" + request.getSession().getId();
    }

    /**
     * 帮助类方法，方便获取HttpServletRequest
     * 
     * @return
     */
    public HttpServletRequest getRequest() {
        HttpServletRequest request = ServletActionContext.getRequest();
        return request;
    }

    public Map<String, String> getPayModeMap() {
        return dataDictService.findMapDataByPrimaryKey("IYOUBOX_FINANCE_PAY_MODE");
    }

    /**
     * 地区列表集合
     * 
     * @return
     */
    public Map<Long, String> getRegionsMap() {
        Map<Long, String> dataMap = new LinkedHashMap<Long, String>();
        List<Region> regions = regionService.findAllCached();
        for (Region item : regions) {
            if (item.getParent() != null
                    && !(item.getParent().getId().equals(0L) && (item.getName().equals("北京市") || item.getName().equals("上海市") || item.getName().equals("天津市") || item.getName()
                            .equals("重庆市")))) {
                dataMap.put(item.getId(), item.getName());
            }

        }
        return dataMap;
    }

    public Map<Long, String> getFloorsMap() {
        Map<Long, String> dataMap = new LinkedHashMap<Long, String>();
        List<Floor> floors = floorService.findAllCached();
        for (Floor item : floors) {

            dataMap.put(item.getId(), item.getMonthText() + ";" + item.getFloorType());
        }
        return dataMap;
    }

    public Map<String, String> findMapDataByDataDictPrimaryKey(String primaryKey) {
        return dataDictService.findMapDataByPrimaryKey(primaryKey);
    }

    /**
     * 快递公司列表集合
     * 
     * @return
     */
    public Map<Long, String> getLogisticsNameMap() {
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "supplierType", SupplierTypeEnum.KD));
        List<Supplier> suppliers = supplierService.findByFilters(groupPropertyFilter);
        Map<Long, String> dataMap = new LinkedHashMap<Long, String>();
        for (Supplier supplier : suppliers) {
            dataMap.put(supplier.getId(), supplier.getDisplay());
        }
        return dataMap;
    }

    /**
     * 供货商列表集合
     * 
     * @return
     */
    public Map<Long, String> getSuppliersMap() {
        Map<Long, String> dataMap = new LinkedHashMap<Long, String>();
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "supplierType", true));
        List<Supplier> suppliers1 = supplierService.findByFilters(groupPropertyFilter);
        for (Supplier item : suppliers1) {
            dataMap.put(item.getId(), item.getDisplay());
        }
        GroupPropertyFilter groupPropertyFilter2 = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter2.append(new PropertyFilter(MatchType.NE, "supplierType", SupplierTypeEnum.KD));
        List<Supplier> suppliers2 = supplierService.findByFilters(groupPropertyFilter2);
        for (Supplier item : suppliers2) {
            dataMap.put(item.getId(), item.getCode() + "-" + item.getDisplay());
        }
        return dataMap;
    }

    /**
     * 仓库列表集合
     * 
     * @return
     */
    public Map<Long, String> getStorageLocationMap() {
        Map<Long, String> dataMap = new LinkedHashMap<Long, String>();
        List<StorageLocation> list = storageLocationService.findAllCached();
        for (StorageLocation item : list) {
            if (!item.getDisabled()) {
                dataMap.put(item.getId(), item.getDisplay());
            }
        }
        return dataMap;
    }

    /**
     * 合作伙伴列表集合
     * 
     * @return
     */
    public Map<Long, String> getPartnersMap() {
        Map<Long, String> partnerMap = new LinkedHashMap<Long, String>();
        Iterable<Partner> partnerList = partnerService.findAll();
        Iterator<Partner> it = partnerList.iterator();
        while (it.hasNext()) {
            Partner partner = it.next();
            partnerMap.put(partner.getId(), partner.getDisplay());
        }
        return partnerMap;
    }

    public Map<Long, String> getAgentPartnersMap() {
        Map<Long, String> partnerMap = new LinkedHashMap<Long, String>();
        Iterable<Partner> partnerList = partnerService.findAll();
        Iterator<Partner> it = partnerList.iterator();
        while (it.hasNext()) {
            Partner partner = it.next();
            if (PartnerTypeEnum.AGENT.equals(partner.getPartnerType())) {
                partnerMap.put(partner.getId(), partner.getDisplay());
            }
        }
        return partnerMap;
    }

    public Map<Long, String> getStockPartnersMap() {
        Map<Long, String> partnerMap = new LinkedHashMap<Long, String>();
        Iterable<Partner> partnerList = partnerService.findAll();
        Iterator<Partner> it = partnerList.iterator();
        while (it.hasNext()) {
            Partner partner = it.next();
            if (PartnerTypeEnum.STOCK.equals(partner.getPartnerType())) {
                partnerMap.put(partner.getId(), partner.getDisplay());
            }
        }
        return partnerMap;
    }

    public Map<String, String> getDepartmentsMap() {
        Map<String, String> departmentsMap = new LinkedHashMap<String, String>();
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        Iterable<Department> departments = departmentService.findByFilters(groupPropertyFilter);
        Iterator<Department> it = departments.iterator();
        while (it.hasNext()) {
            Department department = it.next();
            departmentsMap.put(department.getId(), department.getDisplay());
        }
        return departmentsMap;
    }

    public Map<Long, String> getUsersMap() {
        Map<Long, String> usersMap = new LinkedHashMap<Long, String>();
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "enabled", Boolean.TRUE));
        Iterable<User> users = userService.findByFilters(groupPropertyFilter);
        Iterator<User> it = users.iterator();
        while (it.hasNext()) {
            User user = it.next();
            usersMap.put(user.getId(), user.getDisplay());
        }
        return usersMap;
    }

    public User getLogonUser() {
        return AuthUserHolder.getLogonUser();
    }

    /**
     * 获取必须请求参数sids，并以逗号","切分转换为Long型数组
     * 
     * @return 主键数组
     */
    public Long[] getSelectSids() {
        String sids = this.getRequest().getParameter("ids");
        if (StringUtils.isBlank(sids)) {
            return new Long[0];
        }
        String[] idArray = sids.split(",");
        Long[] ids = new Long[idArray.length];
        for (int i = 0; i < idArray.length; i++) {
            ids[i] = Long.valueOf(idArray[i]);
        }
        return ids;
    }

    /**
     * 品牌列表集合
     * 
     * @return
     */
    public Map<Long, String> getBrandsMap() {
        Map<Long, String> dataMap = new LinkedHashMap<Long, String>();
        List<Brand> brands = brandService.findAllCached();
        for (Brand item : brands) {
            dataMap.put(item.getId(), item.getTitle());
        }
        return dataMap;
    }

    public Map<Long, String> getVipLevelsMap() {
        Map<Long, String> dataMap = new LinkedHashMap<Long, String>();
        List<VipLevel> vipLevels = vipLevelService.findAllCached();
        for (VipLevel item : vipLevels) {
            dataMap.put(item.getId(), item.getName());
        }
        return dataMap;
    }

    public Map<String, String> getCategoryTimelinesMap() {
        List<Category> categories = categoryService.findTimelines();
        Map<String, String> dataMap = new LinkedHashMap<String, String>();
        for (Category category : categories) {
            dataMap.put(category.getName(), category.getName());
        }
        return dataMap;
    }
}
